package icu.thatyear.main.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: littleShop - CaptchaController
 * <p>Powered by 16423 On 2024-12-13 10:00:29
 *
 * @author 16423 [cjy]
 * @version 1.0
 * @since 17
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private final RedisTemplate<String,Object> redisTemplate;

    @Autowired
    public CaptchaController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    // 获取图片验证码
    @GetMapping("/getCaptcha")
    public SaResult createCaptcha(){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 50);
        // 图形验证码写出到指定文件
//        lineCaptcha.write("F:/test/captcha.png");

        UUID uuid = UUID.randomUUID();

        //封装验证码
        HashMap<String,Object> r = new HashMap<>();
        r.put("img",lineCaptcha.getImageBase64());
        r.put("uuid",uuid.toString());

        String upperCode = lineCaptcha.getCode().toUpperCase();
        //将验证码传入redis,2分钟后失效
        redisTemplate.opsForValue().set(uuid.toString(),upperCode,2, TimeUnit.MINUTES);
        return SaResult.data(r);
    }
}